<?php
/**
 * 后台菜单类
 * @Author hugo
 * @Email webmaster@jushare.com
 */
namespace Cpanel\Controller;
use Common\Controller\CpanelController;

class MenuController extends CpanelController
{
    function _initialize()
    {
        parent::_initialize();
        $this->mode = D('Menu');
    }

    /**
     * 菜单列表
     * @param int $parent
     */
    public function query($parent = 0)
    {
        $data = $this->mode->fetchMenu(false, true, $parent);
        $this->ajaxReturn($data);
    }

    /**
     * 树型列表
     */
    public function tree()
    {
        $data = $this->mode->fetchMenu(I('get.isMenu'));
        $type = I('type');
        switch($type)
        {
            case 'select':
                $topMenu[] = array('id' => 0, 'text' => L('top_menu'), 'pid' => 0, 'href' => '');
                $data = array_merge($topMenu, $data);
                break;
            default:
                $selectedItem = base64_decode(I('selected'));
                if(strpos($selectedItem, ','))
                {
                    $selectedItem = explode(',', $selectedItem);
                }else{
                    $selectedItem = array($selectedItem);
                }
                foreach($data as $key => $row)
                {
                    if(in_array($row['id'], $selectedItem))
                    {
                        $row['checked'] = true;
                    }
                    $data[$key] = $row;
                }
                break;
        }
        $data = \Library\Tree::treeArray($data);
        $this->ajaxReturn($data);
    }

    public function item()
    {
        $itemid = I('itemid');
        $data = $this->mode->find($itemid);
        $this->ajaxReturn($data);
    }

    public function drop()
    {
        $items = explode(',', I('items'));
        foreach($items as $itemid)
        {
            if($this->mode->where("parent_id = '%d'", $itemid)->count() > 0)
            {
                $message = L('delete_error');
            }else{
                $this->mode->delete($itemid);
            }
        }
        if(empty($message))
        {
            $this->success();
        }else{
            $this->error($message);
        }
    }

    public function _before_save()
    {
        $data = I('post.');
        $data['menu_name'] or $this->error(L('menu_name_lost'));
        $data['class_name'] or $this->error(L('class_name_lost'));
        $condition = array();
        if(isset($data['menu_id']))
        {
            $data['menu_id'] or $this->error(L('primary_lost'));
            $condition['menu_id'] = array('neq', $data['menu_id']);
        }
        $condition['menu_name'] = $data['menu_name'];
        $condition['parent_id'] = $data['parent_id'];
        $total = $this->mode->where($condition)->count();
        if($total > 0) $this->error(L('menu_name_exists'));
    }
}